<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    @ok="handleSubmit"
    @cancel="close"
    style="top:50px"
    cancelText="关闭"
  >
    <template slot="footer">
      <a-button type="primary" @click="handleSubmit">确认</a-button>
      <a-button @click="close">取消</a-button>
    </template>
    <a-spin tip="Loading..." :spinning="loading">
      <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px">
        <a-col :md="12" :sm="24">
          <a-card :bordered="false">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <a-col :xl="7" :lg="6" :md="6" :sm="24">
                  <a-form-item label="公司编号">
                    <a-input placeholder="请输入" v-model="queryParam.companyCode"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :xl="7" :lg="6" :md="6" :sm="24">
                  <a-form-item label="公司名称">
                    <a-input placeholder="请输入" v-model="queryParam.companyName"></a-input>
                  </a-form-item>
                </a-col>

                <div style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-col :xl="4" :lg="6" :md="6" :sm="24">
                    <a-button type="primary" @click="onSearch" icon="search">查询</a-button>
                  </a-col>
                </div>
              </a-row>
            </a-form>
            <a-table
              ref="table"
              size="middle"
              class='Table'
              bordered
              :scroll="{
          x:'max-content'
        }"
              tableLayout="auto"
              rowKey="companyCode"
              :columns="positionsColumns"
              :dataSource="positions"
              :pagination="ipagination"
              :loading="loading"

              :rowSelection="{selectedRowKeys: companySelectedRowKeys,onSelect: onSelect,onSelectAll:onSelectAll}"
              @change="handleTableChange"
            >
<!--              :customRow="customRowFn"-->
              <template slot="mainPosition" slot-scope="text, record, index" v-if="false">
                {{ text }}
              </template>
              <template slot="imgUrl" slot-scope="text, record, index">
                <div class="anty-img-wrap">
                  <a-avatar shape="square" :src="record.imgUrl" icon="user" />
                </div>
              </template>

              <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>
            </a-table>

          </a-card>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-card :bordered="false">
            <a-table
              ref="table"
              size="middle"
              class='Table'
              bordered
              :scroll="{
          x:'max-content'
        }"
              tableLayout="auto"
              rowKey="companyCode"
              :columns="positionsDataColumns"
              :dataSource="companysData"
            >

              <template slot="mainPosition" slot-scope="text, record, index">
                <a-radio-group v-model="record.mainPosition" @change="onPositionChange">
                  <a-radio :value="0">
                    主职
                  </a-radio>
                  <a-radio :value="1">
                    副职
                  </a-radio>
                </a-radio-group>
              </template>
              <template slot="imgUrl" slot-scope="text, record, index">
                <div class="anty-img-wrap">
                  <a-avatar shape="square" :src="record.imgUrl" icon="user" />
                </div>
              </template>

              <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>

              <template slot="action" slot-scope="text, record, index">
                <a @click="handleDelete(record)">删除</a>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </a-spin>
  </j-modal>
</template>

<script>
import { filterObj } from '@/utils/util'
import { getAction, postAction } from '@api/manage'

export default {
  name: 'selectCompany',
  props: {
    modalWidth: {
      type: String || number
    },
    visible: {
      type: Boolean,
      default: false,
      required: false
    },
    title: {
      type: String,
      default: '公司选择'

    }
    // currentData:Array,
    // visible:Boolean,
    // termCustCode:String
  },
  activated() {
    console.log('aaaa')
  },
  mounted() {
    this.loadData(1)
  },
  data() {
    return {

      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      activeKey: 'company',
      typeLoading: false,
      queryParam: {},
      positions: [],
      companysData: [],
      positionsColumns: [
        {
          title: '#',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '公司编号',
          align: 'center',
          dataIndex: 'companyCode'
        },
        {
          title: '公司名称',
          align: 'center',
          dataIndex: 'companyName'
        },


        // {
        //     title: '操作',
        //     align: 'center',
        //     dataIndex: 'action',
        //     width: 80,
        //     ellipsis: true,
        //     scopedSlots: {customRender: 'action'},
        // },
      ],
      positionsDataColumns: [
        {
          title: '#',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '公司编号',
          align: 'center',
          dataIndex: 'companyCode'
        },
        {
          title: '公司名称',
          align: 'center',
          dataIndex: 'companyName'
        },
        // {
        //     title: '职位级别',
        //     align: 'center',
        //     dataIndex: 'positionLevel'
        // },
        // {
        //     title: '职位类型',
        //     align: 'center',
        //     dataIndex: 'mainPosition',
        //     scopedSlots: {customRender: 'mainPosition'},
        // },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          width: 80,
          ellipsis: true,
          scopedSlots: { customRender: 'action' }
        }
      ],
      companySelectedRowKeys: [],
      companySelectionRows: [],
      loading: false,
      userInfo: this.$store.getters.userInfo,
      record: null,
      url: {
        list: window._CONFIG['domianURL'] + '/company/getPageList'
      },
      custCode: ''

    }
  },
  computed: {
    // positionsData: {
    //   get() {
    //     this['positionSelectedRowKeys'] = this.currentData.map(row => row.positionCode)
    //     this['positionSelectionRows'] = this.currentData
    //     return this.currentData
    //   },
    //   set(v) {
    //     // this['positionSelectedRowKeys'] = v.map(row => row.positionCode);
    //     // this['positionSelectionRows'] = v
    //     this.$emit('currentData:update', v)
    //   }
    // },
    // custCode: {
    //   get() {
    //     return this.termCustCode
    //   }
    // }
  },
  created() {
    // 该方法触发屏幕自适应

    this.resetScreenSize()
  },
  methods: {
    // customRowFn(record) {
    //   return {
    //     on: {
    //       click: () => {
    //         let key = record[this.activeKey]
    //           let index = this.companySelectedRowKeys.indexOf(key)
    //           if (index === -1) {
    //             this.positions =
    //             this.companySelectedRowKeys.push(key)
    //             this.companySelectionRows.push(record)
    //             this.companysData.push(record)
    //           } else {
    //             this.companySelectedRowKeys.remove(key)
    //             this.companySelectionRows.remove(record)
    //             this.companysData.remove(record)
    //           }
    //         }
    //       }
    //     }
    // },
    showlist(code) {
      let p1 = new Promise((re, rj) => {
        this.loadData(1)
        re(code)
      })
      p1.then(re => {
        console.log(re)

        let url = window._CONFIG['domianURL'] + '/company/getCustByIdOrCustCode'
        getAction(url, { custCode: code }).then((res) => {
          this.custCode = re
          this.companysData = res.result || []

          console.log(this.companysData)
          this[this.activeKey + 'SelectionRows'] = this.companysData
          this[this.activeKey + 'SelectedRowKeys'] =this.companysData.map(item =>{return item.companyCode})
        })
      }).catch(err => {
        console.log(res.message)
      })
    },
    handleSubmit() {
      let that = this
      let params = {
        companyVos: this.companysData,
        custCode: this.custCode
      }
      let url = window._CONFIG['domianURL'] + '/company/saveCustByCompany'
      postAction(url, params).then(res => {
        if (!res.success) {
          this.$message.error(res.message)
          return
        }
        that.close()
      })
      // let that = this;
      // that.$emit('ok', this.positionsData,this.reqCode);
      // that.searchReset(0)

    },
    close() {
      this.searchReset(0)
      this.$emit('okCompany')

    },
    /**
     * 删除已选中商品
     * @param record
     */
    handleDelete(record) {
      this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
      this[this.activeKey + 'SelectionRows'].removeByCode(record, this.activeKey + 'Code')
      this[this.activeKey + 'SelectedRowKeys'].remove(record[this.activeKey + 'Code'])
    },
    // 触发屏幕自适应
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.scrollTrigger = { x: 800 }
      } else {
        this.scrollTrigger = {}
      }
    },
    /**
     * 获取查询参数
     * @returns {*}
     */
    getQueryParams() {
      let param = Object.assign({}, this.queryParam)
      param.current = this.ipagination.current
      param.custCode = this.termCustCode
      param.size = this.ipagination.pageSize
      return filterObj(param)
    },
    searchReset(num) {
      let that = this
      if (num !== 0) {
        that.loadData(1)
      }
      that[this.activeKey + 'SelectedRowKeys'] = []
      that[this.activeKey + 'SelectionRows'] = []
      that[this.activeKey + 'sData'] = []
    },
    /**
     * 手动全选/取消全选分类
     * @param selected
     * @param selectedRows
     * @param changeRows
     */
    onSelectAll(selected, selectedRows, changeRows) {
      this[this.activeKey + 'SelectedRowKeys'] = selectedRows.map(row => row.code)
      this[this.activeKey + 'SelectionRows'] = selectedRows
      if (selected) {
        //todo 选中
        changeRows.map(row => {
          this[this.activeKey + 'sData'].push(row)
        })
      } else {
        //todo 取消选中
        changeRows.map(row => {
          this[this.activeKey + 'sData'].removeByCode(row, this.activeKey + 'Code')
        })
      }
    },

    /**
     * 手动勾选/取消分类
     * @param record
     * @param selected
     * @param selectedRows
     * @param nativeEvent
     */
    onSelect(record, selected, selectedRows, nativeEvent) {
      this[this.activeKey + 'SelectedRowKeys'] = selectedRows.map(row => row[this.activeKey + 'Code'])
      this[this.activeKey + 'SelectionRows'] = selectedRows.slice(0)
      if (selected) {
        //todo 选中
        this[this.activeKey + 'sData'].push({ ...record })
      } else {
        //todo 取消选中
        this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
      }

    },
    onSearch() {
      this.loadData(1)
    },

    /**
     * 覆盖mixin的loadData方法
     * @param arg
     * @returns {Promise<void>}
     */
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      // let url = window._CONFIG['domianURL'] + '/company/getPageList'
      this.loading = true
      let params = this.getQueryParams()//查询条件
      postAction(this.url.list, { ...params }).then((res) => {
        if (res.success) {
          // this[this.activeKey + 's'] = res.result.records.map(row => Object.assign({}, row, {
          //   mainPosition: 0
          // }))
          this.positions = res.result.records
          this.ipagination.total = res.result.total
          this.loading = false
        }
      }).finally(() => {
        this.loading = false
      })
    },

    handleTableChange(pagination, filters, sorter) {
      console.log('556')
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    }
    //
    // setData(){
    //     this.$emit('getPosition',this.positionsData)
    // }
  }
}
</script>

<style scoped>

</style>
